package com.sisi.web;

import entity.User816;
import util.JavaUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/user816")
public class User816Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method) {
            case "login" :
                login(req,resp);
                break;
            case "logout" :
                logout(req,resp);
                break;
        }

    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {//登出的servlet
        System.out.println("User816Servlet.logout");
        HttpSession session = req.getSession();//获取session
        session.invalidate();//将session销毁
        resp.sendRedirect(req.getContextPath() + "/login.jsp");//跳转到登录页面
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        System.out.println("UserServlet");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        User816 user816 = null;
        try {
            connection = JavaUtil.getConnection();
            String sql = "SELECT id,name,password,age,level FROM user816 WHERE name=? AND password=?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            statement.setString(2,password);
            resultSet = statement.executeQuery();
            if (resultSet.next()){
                int id = resultSet.getInt("id");
                int age = resultSet.getInt("age");
                int level = resultSet.getInt("level");
                user816 = new User816(id,name,password,age,level);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JavaUtil.close(connection,statement,resultSet);
        }

        if (user816 != null){
            HttpSession session = req.getSession();//创建session
            session.setAttribute("user816",user816);//用session设置变量
            resp.sendRedirect(req.getContextPath() + "/");//登录成功跳转到首页
        } else {
            resp.sendRedirect(req.getContextPath() + "/fail.html");//没查询到跳转页面
        }

    }
}
